import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import {Message} from "element-ui";
import {getUserInfo} from "../network/viewsRequest/user";
import {WHITE_LIST, UNAUTHORIZED_LIST, UNSHOWN_IN_MENU_LIST} from "../common/const";


Vue.use(VueRouter);

const Dashboard = () => import('views/baseView/Dashboard');
const ChangePassword = () => import('views/baseView/ChangePassword');
const Unauthorized = () => import('views/baseView/Unauthorized');
const Error = () => import('views/baseView/Error');

const HomeView = () => import('views/homeView/HomeView');
const ArticleView = () => import('views/articleView/ArticleView');
const CategoryView = () => import('views/categoryView/CategoryView');
const CarouselView = () => import('views/carouselView/CarouselView');
const CommentView = () => import('views/commentView/CommentView');
const NoticeView = () => import('views/noticeView/NoticeView');
const TagView = () => import('views/tagView/TagView');
const UserView = () => import('views/userView/UserView');
const RoleView = () => import('views/roleView/RoleView');

const LoginView = () => import('views/baseView/LoginView');
const MainLayout = () => import('components/content/mainlayout/MainLayout');

const Markdown = () => import('views/articleView/subView/MarkdownView');
const RichEditor = () => import('views/articleView/subView/RichEditorView');
const SaveImage = () => import('views/carouselView/subView/SaveImageView')



const routes = [{
  path: '',
  redirect: '/login'
}, {
  path: '/login',
  component: LoginView
}, {
  path: '/unauthorized',
  component: Unauthorized
}, {
  path: '/error',
  component: Error
}, {
  path: '/dashboard',
  component: MainLayout,
  children: [{
    path: '',
    component: Dashboard
  }, {
    path: 'changePassword',
    component: ChangePassword
  }, {
    path: 'home',
    component: HomeView
  }, {
    path: 'article',
    component: ArticleView
  }, {
    path: 'article/markdown',
    component: Markdown
  }, {
    path: 'article/richeditor',
    component: RichEditor
  }, {
    path: 'category',
    component: CategoryView
  }, {
    path: 'carousel',
    component: CarouselView
  }, {
    path: 'carousel/saveimage',
    component: SaveImage
  }, {
    path: 'comment',
    component: CommentView
  }, {
    path: 'notice',
    component: NoticeView
  }, {
    path: 'tag',
    component: TagView
  }, {
    path: 'user',
    component: UserView
  }, {
    path: 'role',
    component: RoleView
  }]
}]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  window.setTimeout(() => {
    // 如果token有值
    if (store.state.token) {
      if (to.path === '/login') { // 登录情况下访问登录页，不允许访问，直接跳到首页
        next('/dashboard');
      } else if (to.path === '/unauthorized') {
        next();
      } else { // 其他情况下发送请求到服务端去拿当前用户的安全数据
        getUserInfo().then(res => {
          if (res.code == 1) {
            // 检查用户有没有访问该页面的权限
            if (UNAUTHORIZED_LIST.indexOf(to.path) !== -1) { // 登录用户都能访问dashboard和changePassword
              store.commit("assignCurrentUser", res.data);
              next();
              return;
            }
            let allowedMenus = res.data.permissionMap.menus;
            let allowedButtons = res.data.permissionMap.buttons;
            let allowedUrls = allowedMenus.map(item => {
              return item.to;
            });
            // 如果在buttons中包含了article:insert或者carousel:insert，要在allowedUrls中添加相应的可访问链接
            insertExtraAllowedUrls(allowedUrls, allowedButtons);
            if (allowedUrls.indexOf(to.path) == -1) { // 没有权限
              next('/unauthorized');
            } else { // 有权限
              // 给当前用户赋值
              store.commit("assignCurrentUser", res.data);
              store.commit("getCommentForUnchecked");
              next();
            }

          } else {
            // 过期的情况
            Message.error("登录失败，请重新登录");
            store.commit("clearCurrentUser");
            next("/login");
          }
        })
      }
    } else { // 如果token没值，访问的页面是登录页
      if (WHITE_LIST.indexOf(to.path) !== -1) {
        next();
      } else {
        next('/login');
      }
    }
  }, 10);

})

// 如果在buttons中包含了article:insert或者carousel:insert，要在allowedUrls中添加相应的可访问链接
function insertExtraAllowedUrls(allowedUrls, allowedButtons) {
  for (let item of UNSHOWN_IN_MENU_LIST) {
    for (let button of allowedButtons) {
      if (item.permission === button) {
        allowedUrls.push(...item.url);
        break;
      }
    }
  }
}

export default router
